package com.etang.shhomeproject.appstart.loginandregist;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.etang.shhomeproject.R;
import com.etang.shhomeproject.tools.toast.DiyToast_k;
import com.etang.shhomeproject.tools.sql.MyDataBaseHelper;

public class RegActivity extends AppCompatActivity {
    public static Activity activity;
    private Button btn_reg_con;
    private EditText et_user, et_pass;
    private SQLiteDatabase db;
    private MyDataBaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getOrientation(RegActivity.this);
        activity = this;
        initView();
        btn_reg_con.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_pass.getText().toString().isEmpty() || et_user.getText().toString().isEmpty()) {
                    DiyToast_k.showToast(RegActivity.this, "不能有空白项");
                } else {
                    Cursor cursor = db.rawQuery("select * from user where username = ?", new String[]{et_user.getText().toString()});
                    if (cursor.moveToNext()) {
                        DiyToast_k.showToast(RegActivity.this, "用户已存在");
                    } else {
                        db.execSQL("insert into user (username,passward)values(?,?)",
                                new String[]{et_user.getText().toString(), et_pass.getText().toString()});
                        DiyToast_k.showToast(RegActivity.this, "注册成功");
                        finish();
                    }
                }
            }
        });
    }

    private void initView() {
        btn_reg_con = (Button) findViewById(R.id.btn_reg_con);
        et_pass = (EditText) findViewById(R.id.et_reg_passward);
        et_user = (EditText) findViewById(R.id.et_reg_username);
        dbHelper = new MyDataBaseHelper(this, "info.db", null, 2);
        db = dbHelper.getWritableDatabase();
    }

    public static void reg_exit(View view) {
        activity.finish();
    }

    private void getOrientation(Context ctx) {
        if (ctx.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            //竖屏
            setContentView(R.layout.activity_reg_portrait);
        } else {
            //横屏
            setContentView(R.layout.activity_reg_landscape);
        }
    }
}